package service

import (
	"regexp"
	"strings"
	"unicode/utf8"
)

// SentenceSplitter 句子分割器
type SentenceSplitter struct{}

// NewSentenceSplitter 创建句子分割器
func NewSentenceSplitter() *SentenceSplitter {
	return &SentenceSplitter{}
}

// SplitIntoSentences 智能句子分割
func (s *SentenceSplitter) SplitIntoSentences(text string) []string {
	// 首先按中文标点分割
	sentences := s.splitByChineseDelimiters(text)
	
	// 然后按英文标点进一步分割
	var result []string
	for _, sentence := range sentences {
		englishSentences := s.splitByEnglishDelimiters(sentence)
		result = append(result, englishSentences...)
	}
	
	// 过滤空句子并清理
	var filtered []string
	for _, sentence := range result {
		cleaned := strings.TrimSpace(sentence)
		if cleaned != "" && utf8.ValidString(cleaned) {
			filtered = append(filtered, cleaned)
		}
	}
	
	return filtered
}

// splitByChineseDelimiters 按中文标点分割
func (s *SentenceSplitter) splitByChineseDelimiters(text string) []string {
	// 改进的中文句子分割正则表达式
	// 考虑引号、括号等配对标点
	pattern := `([。！？…]+)(['"」'）\)\]}》]*\s*)`
	regex := regexp.MustCompile(pattern)
	
	matches := regex.FindAllStringSubmatchIndex(text, -1)
	
	var sentences []string
	start := 0
	
	for _, match := range matches {
		end := match[1]
		if end > start {
			sentence := strings.TrimSpace(text[start:end])
			if sentence != "" {
				sentences = append(sentences, sentence)
			}
		}
		start = end
	}
	
	// 添加剩余部分
	if start < len(text) {
		remaining := strings.TrimSpace(text[start:])
		if remaining != "" {
			sentences = append(sentences, remaining)
		}
	}
	
	return sentences
}

// splitByEnglishDelimiters 按英文标点分割
func (s *SentenceSplitter) splitByEnglishDelimiters(text string) []string {
	// 改进的英文句子分割
	pattern := `([.!?]+)(\s*["'\)\]]*\s*)`
	regex := regexp.MustCompile(pattern)
	
	matches := regex.FindAllStringSubmatchIndex(text, -1)
	
	var sentences []string
	start := 0
	
	for _, match := range matches {
		end := match[1]
		
		// 检查是否是缩写
		if s.isLikelyAbbreviation(text[start:match[0]+1]) {
			continue
		}
		
		if end > start {
			sentence := strings.TrimSpace(text[start:end])
			if sentence != "" {
				sentences = append(sentences, sentence)
			}
		}
		start = end
	}
	
	// 添加剩余部分
	if start < len(text) {
		remaining := strings.TrimSpace(text[start:])
		if remaining != "" {
			sentences = append(sentences, remaining)
		}
	}
	
	return sentences
}

// isLikelyAbbreviation 检查是否可能是缩写
func (s *SentenceSplitter) isLikelyAbbreviation(text string) bool {
	// 常见缩写模式
	abbreviations := []string{
		`\b[A-Z][a-z]*\.`,           // Mr. Dr. etc.
		`\b[A-Z]\.`,                 // 单字母缩写
		`\b\d+\.\d+`,                // 数字（如版本号）
		`\b(etc|vs|al|cf|eg|ie)\.`,  // 常见拉丁缩写
	}
	
	for _, pattern := range abbreviations {
		if matched, _ := regexp.MatchString(pattern, text); matched {
			return true
		}
	}
	
	return false
}